// lib/widgets/community_list_widget.dart
import 'package:flutter/material.dart';
import '../../../models/community.dart';

class CommunityListWidget extends StatelessWidget {
  final List<Community> communities;
  final Function(int?) onCommunityTap; // **新增：点击回调函数**
  final int? selectedCommunityId; // **新增：用于标记当前选中社区的ID**

  const CommunityListWidget({
    super.key,
    required this.communities,
    required this.onCommunityTap, // **新增：需要传入回调函数**
    this.selectedCommunityId, // **新增：可选的选中ID**
  });

  @override
  Widget build(BuildContext context) {
    if (communities.isEmpty) {
      return const Center(child: Text('暂无社区数据'));
    }

    // 为了在社区列表顶部添加一个“全部”社区的选项
    List<Community> displayCommunities = [
      Community(communityId: null, communityName: '全部'), // 代表所有社区的选项
      ...communities,
    ];

    return SizedBox(
      height: 120,
      child: GridView.builder(
        scrollDirection: Axis.horizontal,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 1.2,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
        ),
        itemCount: displayCommunities.length, // 使用包含“全部”的列表
        itemBuilder: (context, index) {
          final community = displayCommunities[index];
          final bool isSelected = community.communityId == selectedCommunityId; // 判断是否选中

          return GestureDetector(
            onTap: () {
              onCommunityTap(community.communityId); // **调用回调函数**
            },
            child: Card(
              elevation: 2,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
                // **新增：根据选中状态改变边框颜色**
                side: isSelected
                    ? const BorderSide(color: Colors.blue, width: 2)
                    : BorderSide.none,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircleAvatar(
                    radius: 20,
                    backgroundColor: isSelected ? Colors.blue : Colors.blueGrey, // 选中时颜色变化
                    child: Icon(
                      community.communityId == null ? Icons.apps : Icons.people, // “全部”显示Apps图标，其他显示People
                      color: Colors.white,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    community.communityName ?? '未知社区',
                    style: const TextStyle(fontSize: 14),
                    textAlign: TextAlign.center,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}